<template>
  <div class="user-management">
    <div class="header">
      <h2>회원 관리</h2>
      <div class="actions">
        <el-input v-model="search" placeholder="로그인 ID, 이메일, 이름, 닉네임 또는 휴대폰 번호 검색" clearable style="width: 360px" @keyup.enter.native="fetchUsers" />
        <el-select v-model="status" placeholder="상태" clearable style="width:120px" @change="handleFilterChange">
          <el-option label="정상" value="active" />
          <el-option label="비활성화됨" value="banned" />
        </el-select>
        <el-select v-model="role" placeholder="역할" clearable style="width:140px" @change="handleFilterChange">
          <el-option label="일반 사용자" value="user" />
          <el-option label="파트너" value="partner" />
          <el-option label="관리자" value="admin" />
        </el-select>
        <el-select v-model="memberLevel" placeholder="회원 등급" clearable style="width:140px" @change="handleFilterChange">
          <el-option
            v-for="level in memberLevels"
            :key="level.value"
            :label="level.name"
            :value="level.value"
          />
        </el-select>
        <el-button v-if="!referrerId" type="primary" @click="fetchUsers">조회</el-button>
        <el-button v-if="referrerId" type="warning" plain @click="clearReferrer">필터 제거</el-button>
      </div>
    </div>

    <el-alert v-if="referrerId" :title="`현재 필터: 파트너 ${referrerName || referrerId}`" type="info" show-icon :closable="false" style="margin-bottom: 12px" />

    <div class="stats">
      <el-statistic title="총 사용자 수" :value="total" />
    </div>

    <el-table :data="users" v-loading="loading" style="width: 100%">
      <el-table-column prop="loginId" label="로그인 ID" min-width="160" show-overflow-tooltip />
      <el-table-column prop="email" label="이메일" min-width="200" show-overflow-tooltip />
      <el-table-column label="이름/닉네임" min-width="180" show-overflow-tooltip>
        <template #default="{ row }">
          <div>
            <div v-if="row.name">{{ row.name }}</div>
            <div v-if="row.nickname" class="sub">{{ row.nickname }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="역할" width="120">
        <template #default="{ row }"><el-tag :type="roleType(row.role)">{{ roleLabel(row.role) }}</el-tag></template>
      </el-table-column>
      <el-table-column prop="memberLevel" label="회원 등급" width="120">
        <template #default="{ row }"><el-tag :type="memberLevelType(row.memberLevel)">{{ memberLevelLabel(row.memberLevel) }}</el-tag></template>
      </el-table-column>
      <el-table-column prop="status" label="상태" width="120">
        <template #default="{ row }"><el-tag :type="row.status === 'active' ? 'success' : 'info'">{{ row.status === 'active' ? '정상' : '비활성화됨' }}</el-tag></template>
      </el-table-column>
      <el-table-column label="추천인" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.referrer">
            <span class="referrer">{{ row.referrer.loginId }}</span>
            <el-tag v-if="row.referrer.partnerProfile?.referralCode" class="mono" effect="plain">{{ row.referrer.partnerProfile.referralCode }}</el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="체험 상태" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.trial" :type="row.trial.ended ? 'danger' : 'warning'">
            {{ row.trial.ended ? '종료됨' : '진행 중' }}
          </el-tag>
          <el-tag v-else type="info">시작 안 함</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="포인트 잔액" width="120">
        <template #default="{ row }"><span class="mono green">{{ formatPoints(row.wallet?.pointsBalance) }}</span></template>
      </el-table-column>
      <el-table-column prop="createdAt" label="가입 시간" width="180">
        <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="작업" width="520" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openView(row)">보기</el-button>
          <el-button size="small" @click="openEdit(row)" v-if="isAdmin">편집</el-button>
          <el-button v-if="isAdmin || isPartner" size="small" type="primary" @click="openAddPoints(row)">포인트 추가</el-button>
          <el-button v-if="isAdmin || isPartner" size="small" type="warning" @click="openSubtractPoints(row)" :disabled="Number(row.wallet?.pointsBalance || 0) <= 0">포인트 차감</el-button>
          <el-button v-if="isAdmin" size="small" type="success" @click="openEditMemberLevel(row)">등급 수정</el-button>
          <el-button v-if="isAdmin" size="small" :type="row.status === 'active' ? 'danger' : 'success'" @click="toggleStatus(row)">{{ row.status === 'active' ? '비활성화' : '활성화' }}</el-button>
          <el-button v-if="isAdmin" size="small" type="info" @click="resetTrialForUser(row)" :loading="trialLoading">체험 재설정</el-button>
          <el-button v-if="isAdmin && row.role !== 'admin'" size="small" type="danger" @click="deleteUser(row)" :disabled="row.role === 'admin'">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="fetchUsers"
      />
    </div>

    <el-dialog v-model="showDialog" title="사용자 상세 정보" width="720px">
      <el-descriptions v-if="detail" :column="2" border>
        <el-descriptions-item label="로그인 ID">{{ detail.loginId }}</el-descriptions-item>
        <el-descriptions-item label="이메일">{{ detail.email }}</el-descriptions-item>
        <el-descriptions-item label="성명">{{ detail.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="닉네임">{{ detail.nickname || '-' }}</el-descriptions-item>
        <el-descriptions-item label="휴대폰 번호">{{ detail.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="성별">{{ genderLabel(detail.gender) }}</el-descriptions-item>
        <el-descriptions-item label="생일">{{ detail.birthdate ? formatDate(detail.birthdate) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="역할"><el-tag :type="roleType(detail.role)">{{ roleLabel(detail.role) }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="상태"><el-tag :type="detail.status === 'active' ? 'success' : 'info'">{{ detail.status === 'active' ? '정상' : '비활성화됨' }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="회원 등급"><el-tag :type="memberLevelType(detail.memberLevel)">{{ memberLevelLabel(detail.memberLevel) }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="가입 시간">{{ formatDate(detail.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="추천인" :span="2">
          <template v-if="detail.referrer">
            <span>{{ detail.referrer.loginId }}</span>
            <el-tag v-if="detail.referrer.partnerProfile?.referralCode" class="mono" effect="plain">{{ detail.referrer.partnerProfile.referralCode }}</el-tag>
          </template>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="포인트 잔액" :span="2"><span class="mono green">{{ formatPoints(detail.wallet?.pointsBalance) }}</span></el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="showDialog = false">닫기</el-button>
      </template>
    </el-dialog>

    <!-- 사용자 편집 팝업 -->
    <el-dialog v-model="showEditDialog" title="사용자 편집" width="560px">
      <el-form :model="editForm" label-width="90px">
        <el-form-item label="성명">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="닉네임">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="휴대폰 번호">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="성별">
          <el-select v-model="editForm.gender" placeholder="성별 선택" clearable>
            <el-option label="남성" value="male" />
            <el-option label="여성" value="female" />
            <el-option label="기타" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="생일">
          <el-date-picker v-model="editForm.birthdate" type="date" value-format="YYYY-MM-DD" placeholder="날짜 선택" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">취소</el-button>
        <el-button type="primary" :loading="saving" @click="saveUser">저장</el-button>
      </template>
    </el-dialog>

    <!-- 포인트 추가 팝업 -->
    <el-dialog v-model="showAddPointsDialog" title="포인트 추가" width="480px">
      <el-form :model="pointsForm" label-width="100px">
        <el-form-item label="사용자">
          <div class="user-display">
            <strong>{{ selectedUser?.nickname || selectedUser?.name || selectedUser?.loginId }}</strong>
            <span class="current-balance">현재 잔액: {{ formatPoints(selectedUser?.wallet?.pointsBalance || 0) }}</span>
          </div>
        </el-form-item>
        <el-form-item label="추가 포인트" required>
          <el-input-number
            v-model="pointsForm.points"
            :min="1"
            style="width: 100%"
            placeholder="추가할 포인트 수량을 입력하세요"
          />
        </el-form-item>
        <el-form-item label="비고">
          <el-input
            v-model="pointsForm.note"
            type="textarea"
            :rows="3"
            placeholder="포인트 추가 사유 또는 비고 (선택사항)"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddPointsDialog = false">취소</el-button>
        <el-button type="primary" @click="addPoints" :loading="pointsLoading">추가 확인</el-button>
      </template>
    </el-dialog>

    <!-- 포인트 차감 팝업 -->
    <el-dialog v-model="showSubtractPointsDialog" title="포인트 차감" width="480px">
      <el-form :model="pointsForm" label-width="100px">
        <el-form-item label="사용자">
          <div class="user-display">
            <strong>{{ selectedUser?.nickname || selectedUser?.name || selectedUser?.loginId }}</strong>
            <span class="current-balance">현재 잔액: {{ formatPoints(selectedUser?.wallet?.pointsBalance || 0) }}</span>
          </div>
        </el-form-item>
        <el-form-item label="차감 포인트" required>
          <el-input-number
            v-model="pointsForm.points"
            :min="1"
            :max="Math.max(1, Number(selectedUser?.wallet?.pointsBalance || 0))"
            style="width: 100%"
            placeholder="차감할 포인트 수량을 입력하세요"
          />
        </el-form-item>
        <el-form-item label="비고">
          <el-input
            v-model="pointsForm.note"
            type="textarea"
            :rows="3"
            placeholder="포인트 차감 사유 또는 비고 (선택사항)"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSubtractPointsDialog = false">취소</el-button>
        <el-button type="danger" @click="subtractPoints" :loading="pointsLoading">차감 확인</el-button>
      </template>
    </el-dialog>

    <!-- 회원 등급 수정 팝업 -->
    <el-dialog v-model="showMemberLevelDialog" title="회원 등급 수정" width="480px">
      <el-form :model="memberLevelForm" label-width="100px">
        <el-form-item label="사용자">
          <div class="user-display">
            <strong>{{ selectedUser?.nickname || selectedUser?.name || selectedUser?.loginId }}</strong>
            <span class="current-level">현재 등급: {{ memberLevelLabel(selectedUser?.memberLevel || 'regular') }}</span>
          </div>
        </el-form-item>
        <el-form-item label="새 등급" required>
          <el-select v-model="memberLevelForm.memberLevel" placeholder="등급을 선택하세요" style="width: 100%">
            <el-option
              v-for="level in memberLevels"
              :key="level.value"
              :label="level.name"
              :value="level.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showMemberLevelDialog = false">취소</el-button>
        <el-button type="primary" @click="updateMemberLevel" :loading="memberLevelLoading">수정 확인</el-button>
      </template>
    </el-dialog>

</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()


const showEditDialog = ref(false)
const saving = ref(false)
const editForm = ref<{ id?: string; name?: string; nickname?: string; phone?: string; gender?: string | null; birthdate?: string | null }>({})

// 积分管理相关
const showAddPointsDialog = ref(false)
const showSubtractPointsDialog = ref(false)
const pointsLoading = ref(false)
const selectedUser = ref<any>(null)
const pointsForm = ref({
  points: null as number | null,
  note: ''
})

// 회원 등급 관리 관련
const showMemberLevelDialog = ref(false)
const memberLevelLoading = ref(false)
const memberLevels = ref<Array<{ value: string; name: string; weight: number }>>([])
const memberLevelForm = ref({
  memberLevel: ''
})

const openEdit = (row: any) => {
  editForm.value = {
    id: String(row.id),
    name: row.name || '',
    nickname: row.nickname || '',
    phone: row.phone || '',
    gender: row.gender || '',
    birthdate: row.birthdate ? String(row.birthdate).slice(0, 10) : ''
  }
  showEditDialog.value = true
}

const saveUser = async () => {
  if (!editForm.value.id) return
  saving.value = true
  try {
    const payload: any = {
      name: editForm.value.name || null,
      nickname: editForm.value.nickname || null,
      phone: editForm.value.phone || null,
      gender: editForm.value.gender || null,
      birthdate: editForm.value.birthdate || null,
    }
    await request.put(`/api/admin/users/${editForm.value.id}`, payload)
    ElMessage.success('저장 성공')
    showEditDialog.value = false
    fetchUsers()
  } catch (e) {
    ElMessage.error('저장 실패')
  } finally {
    saving.value = false
  }
}

const loading = ref(false)
const users = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const search = ref('')
const status = ref('')
const role = ref('')
const memberLevel = ref('')

const referrerId = computed(() => route.query.referrerId as string | undefined)
const referrerName = computed(() => route.query.referrerName as string | undefined)

const showDialog = ref(false)
const detail = ref<any>(null)

const isAdmin = computed(() => authStore.isAdmin)
const isPartner = computed(() => authStore.isPartner)

const fetchUsers = async () => {
  loading.value = true
  try {
    const params: any = { page: currentPage.value, limit: pageSize.value }
    if (search.value) params.search = search.value
    if (status.value) params.status = status.value
    if (role.value) params.role = role.value
    if (memberLevel.value) params.memberLevel = memberLevel.value
    if (referrerId.value) params.referrerId = referrerId.value

    const resp = await request.get('/api/admin/users', { params })
    users.value = resp.data.users
    total.value = resp.data.total
  } catch (e) {
    ElMessage.error('사용자 가져오기 실패')
  } finally {
    loading.value = false
  }
}

const openView = (row: any) => { detail.value = row; showDialog.value = true }

const toggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(`${row.status === 'active' ? '비활성화' : '활성화'}하시겠습니까?`, '확인', { type: 'warning' })
    await request.put(`/api/admin/users/${row.id}/status`, { status: row.status === 'active' ? 'banned' : 'active' })
    ElMessage.success(`${row.status === 'active' ? '비활성화됨' : '활성화됨'}`)
    fetchUsers()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('작업 실패')
  }
}

const formatDate = (s: string) => new Date(s).toLocaleString('zh-CN')
const formatPoints = (p?: string) => (p ? parseInt(p).toLocaleString() : '0')
const roleLabel = (r: string) => ({ user: '일반 사용자', partner: '파트너', admin: '관리자' } as any)[r] || r
const roleType = (r: string) => (r === 'admin' ? 'danger' : r === 'partner' ? 'warning' : 'info')
const genderLabel = (g?: string) => (g ? { male: '남성', female: '여성', other: '기타' }[g] || g : '-')

// 회원 등급 관련 함수
const memberLevelLabel = (level: string) => {
  const levelMap: Record<string, string> = {
    regular: '일반회원',
    silver: '실버',
    gold: '골드',
    diamond: '다이아',
    vip: 'VIP'
  }
  return levelMap[level] || '일반회원'
}

const memberLevelType = (level: string) => {
  const typeMap: Record<string, string> = {
    regular: 'info',
    silver: '',
    gold: 'warning',
    diamond: 'success',
    vip: 'danger'
  }
  return typeMap[level] || 'info'
}
const handleFilterChange = () => { currentPage.value = 1; fetchUsers() }
const clearReferrer = () => router.replace({ query: { ...route.query, referrerId: undefined, referrerName: undefined } })

// 积分管理函数
const openAddPoints = (user: any) => {
  selectedUser.value = user
  pointsForm.value = { points: null, note: '' }
  showAddPointsDialog.value = true
}

const openSubtractPoints = (user: any) => {
  const currentBalance = Number(user?.wallet?.pointsBalance || 0)
  if (currentBalance <= 0) {
    ElMessage.warning('사용자의 포인트 잔액이 0이므로 차감할 수 없습니다')
    return
  }
  selectedUser.value = user
  pointsForm.value = { points: null, note: '' }
  showSubtractPointsDialog.value = true
}

const addPoints = async () => {
  if (!pointsForm.value.points || pointsForm.value.points <= 0) {
    ElMessage.warning('유효한 포인트 수량을 입력하세요')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedUser.value?.nickname || selectedUser.value?.name || selectedUser.value?.loginId}에게 ${formatPoints(String(pointsForm.value.points))} 포인트를 추가하시겠습니까?`,
      '포인트 추가 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  pointsLoading.value = true
  try {
    await request.post(`/api/admin/users/${selectedUser.value.id}/points/add`, {
      points: pointsForm.value.points,
      note: pointsForm.value.note || '관리자 수동 포인트 추가'
    })

    ElMessage.success('포인트 추가 성공')
    showAddPointsDialog.value = false
    await fetchUsers() // 목록 새로고침
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '포인트 추가 실패')
  } finally {
    pointsLoading.value = false
  }
}

const subtractPoints = async () => {
  if (!pointsForm.value.points || pointsForm.value.points <= 0) {
    ElMessage.warning('유효한 포인트 수량을 입력하세요')
    return
  }

  const currentBalance = Number(selectedUser.value?.wallet?.pointsBalance || 0)
  if (pointsForm.value.points > currentBalance) {
    ElMessage.warning('차감할 포인트가 현재 잔액을 초과할 수 없습니다')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedUser.value?.nickname || selectedUser.value?.name || selectedUser.value?.loginId}에게서 ${formatPoints(String(pointsForm.value.points))} 포인트를 차감하시겠습니까?`,
      '포인트 차감 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  pointsLoading.value = true
  try {
    await request.post(`/api/admin/users/${selectedUser.value.id}/points/subtract`, {
      points: pointsForm.value.points,
      note: pointsForm.value.note || '관리자 수동 포인트 차감'
    })

    ElMessage.success('포인트 차감 성공')
    showSubtractPointsDialog.value = false
    await fetchUsers() // 목록 새로고침
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '포인트 차감 실패')
  } finally {
    pointsLoading.value = false
  }
}

// ========== 试看状态管理 ==========
const trialLoading = ref(false)

async function resetTrialForUser(row: any) {
  try {
    await ElMessageBox.confirm(`사용자 ${row.nickname || row.name || row.loginId}의 체험 상태를 재설정하시겠습니까?`, '재설정 확인', {
      type: 'warning'
    })

    trialLoading.value = true
    await request.post(`/api/admin/users/${row.id}/reset-trial`)
    ElMessage.success('체험 상태가 재설정되었습니다')
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e?.message || '재설정 실패')
    }
  } finally {
    trialLoading.value = false
  }
}

// ========== 회원 등급 관리 ==========
const fetchMemberLevels = async () => {
  try {
    const resp = await request.get('/api/admin/member-levels')
    memberLevels.value = resp.data
  } catch (e) {
    ElMessage.error('회원 등급 목록 가져오기 실패')
  }
}

const openEditMemberLevel = (user: any) => {
  console.log('openEditMemberLevel called with user:', user)
  selectedUser.value = user
  memberLevelForm.value = { memberLevel: user.memberLevel || 'regular' }
  showMemberLevelDialog.value = true
  console.log('showMemberLevelDialog set to:', showMemberLevelDialog.value)
}

const updateMemberLevel = async () => {
  if (!memberLevelForm.value.memberLevel) {
    ElMessage.warning('등급을 선택하세요')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedUser.value?.nickname || selectedUser.value?.name || selectedUser.value?.loginId}의 등급을 ${memberLevelLabel(memberLevelForm.value.memberLevel)}로 변경하시겠습니까?`,
      '등급 변경 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  memberLevelLoading.value = true
  try {
    await request.put(`/api/admin/users/${selectedUser.value.id}/member-level`, {
      memberLevel: memberLevelForm.value.memberLevel
    })

    ElMessage.success('회원 등급이 성공적으로 변경되었습니다')
    showMemberLevelDialog.value = false
    await fetchUsers() // 목록 새로고침
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '등급 변경 실패')
  } finally {
    memberLevelLoading.value = false
  }
}

// 删除用户
const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `"${user.loginId}" 사용자를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.`,
      '사용자 삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    const response = await request.delete(`/api/admin/users/${user.id}`)
    const result = response.data

    if (result.success) {
      ElMessage.success(result.message || '사용자가 삭제되었습니다')
      fetchUsers() // 목록 새로고침
    } else {
      ElMessage.error(result.error || '삭제 실패')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 중 오류가 발생했습니다')
    }
  }
}

onMounted(() => {
  fetchUsers()
  fetchMemberLevels()
})
</script>

<style scoped>
.user-management { padding: 20px; }
.header { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; }
.actions { display:flex; gap:10px; }
.stats { margin-bottom: 12px; }
.sub { font-size: 12px; color: #888; }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; }
.green { color: #28a745; font-weight: 600; }
.pager { display:flex; justify-content:center; padding: 16px 0; }
.referrer { margin-right: 6px; }
.user-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.current-balance {
  font-size: 12px;
  color: #909399;
}
.current-level {
  font-size: 12px;
  color: #909399;
}
</style>
